{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Array operations with ``ein_rearrange``, ``ein_reduce``, and ``ein_repeat``\n",
    "\n",
    "[![Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/brainpy/brainpy/blob/master/docs_version2/tutorial_math/einops_in_brainpy.ipynb)\n",
    "[![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/brainpy/brainpy/blob/master/docs_version2/tutorial_math/einops_in_brainpy.ipynb)\n",
    "\n",
    "We don't write \n",
    "```python\n",
    "y = x.transpose(0, 2, 3, 1)\n",
    "```\n",
    "We write comprehensible code\n",
    "```python\n",
    "y = bm.ein_rearrange(x, 'b c h w -> b h w c')\n",
    "```\n",
    "\n",
    "\n",
    "## What's in this tutorial?\n",
    "\n",
    "- fundamentals: reordering, composition and decomposition of axes\n",
    "- operations: `ein_rearrange`, `ein_reduce`, `ein_repeat`\n",
    "- how much you can do with a single operation!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparations"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.145131Z",
     "start_time": "2025-10-06T04:02:03.139852Z"
    }
   },
   "source": [
    "# Examples are given for numpy. This code also setups ipython/jupyter\n",
    "# so that numpy arrays in the output are displayed as images\n",
    "import numpy\n",
    "\n",
    "import brainpy.math as bm"
   ],
   "outputs": [],
   "execution_count": 51
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load a batch of images to play with"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Please download [the data](./test_images.npy)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.161835Z",
     "start_time": "2025-10-06T04:02:03.155841Z"
    }
   },
   "source": [
    "ims = numpy.load('./test_images.npy', allow_pickle=False)\n",
    "# There are 6 images of shape 96x96 with 3 color channels packed into tensor\n",
    "print(ims.shape, ims.dtype)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(6, 96, 96, 3) float64\n"
     ]
    }
   ],
   "execution_count": 52
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.193440Z",
     "start_time": "2025-10-06T04:02:03.189557Z"
    }
   },
   "source": [
    "# display the first image (whole 4d tensor can't be rendered)\n",
    "ims[0].shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96, 3)"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 53
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.220098Z",
     "start_time": "2025-10-06T04:02:03.215283Z"
    }
   },
   "source": [
    "# second image in a batch\n",
    "ims[1].shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96, 3)"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 54
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.243209Z",
     "start_time": "2025-10-06T04:02:03.237539Z"
    }
   },
   "source": [
    "# rearrange, as its name suggests, rearranges elements\n",
    "# below we swapped height and width.\n",
    "# In other words, transposed first two axes (dimensions)\n",
    "bm.ein_rearrange(ims[0], 'h w c -> w h c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96, 3)"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 55
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Composition of axes\n",
    "transposition is very common and useful, but let's move to other capabilities provided by einops"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.264278Z",
     "start_time": "2025-10-06T04:02:03.258754Z"
    }
   },
   "source": [
    "# einops allows seamlessly composing batch and height to a new height dimension\n",
    "# We just rendered all images by collapsing to 3d tensor!\n",
    "bm.ein_rearrange(ims, 'b h w c -> (b h) w c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(576, 96, 3)"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 56
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.298383Z",
     "start_time": "2025-10-06T04:02:03.290603Z"
    }
   },
   "source": [
    "# or compose a new dimension of batch and width\n",
    "bm.ein_rearrange(ims, 'b h w c -> h (b w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 57
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.349972Z",
     "start_time": "2025-10-06T04:02:03.343754Z"
    }
   },
   "source": [
    "# resulting dimensions are computed very simply\n",
    "# length of newly composed axis is a product of components\n",
    "# [6, 96, 96, 3] -> [96, (6 * 96), 3]\n",
    "bm.ein_rearrange(ims, 'b h w c -> h (b w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 58
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.381537Z",
     "start_time": "2025-10-06T04:02:03.376132Z"
    }
   },
   "source": [
    "# we can compose more than two axes. \n",
    "# let's flatten 4d array into 1d, resulting array has as many elements as the original\n",
    "bm.ein_rearrange(ims, 'b h w c -> (b h w c)').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(165888,)"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 59
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Decomposition of axis"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.401562Z",
     "start_time": "2025-10-06T04:02:03.396309Z"
    }
   },
   "source": [
    "# decomposition is the inverse process - represent an axis as a combination of new axes\n",
    "# several decompositions possible, so b1=2 is to decompose 6 to b1=2 and b2=3\n",
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> b1 b2 h w c ', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2, 3, 96, 96, 3)"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 60
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.418841Z",
     "start_time": "2025-10-06T04:02:03.414046Z"
    }
   },
   "source": [
    "# finally, combine composition and decomposition:\n",
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> (b1 h) (b2 w) c ', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(192, 288, 3)"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 61
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.436103Z",
     "start_time": "2025-10-06T04:02:03.431121Z"
    }
   },
   "source": [
    "# slightly different composition: b1 is merged with width, b2 with height\n",
    "# ... so letters are ordered by w then by h\n",
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> (b2 h) (b1 w) c ', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(288, 192, 3)"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 62
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.455386Z",
     "start_time": "2025-10-06T04:02:03.450416Z"
    }
   },
   "source": [
    "# move part of width dimension to height. \n",
    "# we should call this width-to-height as image width shrunk by 2 and height doubled. \n",
    "# but all pixels are the same!\n",
    "# Can you write reverse operation (height-to-width)?\n",
    "bm.ein_rearrange(ims, 'b h (w w2) c -> (h w2) (b w) c', w2=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(192, 288, 3)"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 63
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Order of axes matters"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.471749Z",
     "start_time": "2025-10-06T04:02:03.466435Z"
    }
   },
   "source": [
    "# compare with the next example\n",
    "bm.ein_rearrange(ims, 'b h w c -> h (b w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 64
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.489992Z",
     "start_time": "2025-10-06T04:02:03.485139Z"
    }
   },
   "source": [
    "# order of axes in composition is different\n",
    "# rule is just as for digits in the number: leftmost digit is the most significant, \n",
    "# while neighboring numbers differ in the rightmost axis.\n",
    "\n",
    "# you can also think of this as lexicographic sort\n",
    "bm.ein_rearrange(ims, 'b h w c -> h (w b) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 65
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.506702Z",
     "start_time": "2025-10-06T04:02:03.502141Z"
    }
   },
   "source": [
    "# what if b1 and b2 are reordered before composing to width?\n",
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> h (b1 b2 w) c ', b1=2).shape "
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 66
  },
  {
   "cell_type": "code",
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.524014Z",
     "start_time": "2025-10-06T04:02:03.519083Z"
    }
   },
   "source": [
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> h (b2 b1 w) c ', b1=2).shape "
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 67
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Meet einops.reduce\n",
    "\n",
    "In einops-land you don't need to guess what happened\n",
    "```python\n",
    "x.mean(-1)\n",
    "```\n",
    "Because you write what the operation does\n",
    "```python\n",
    "bm.ein_reduce(x, 'b h w c -> b h w', 'mean')\n",
    "```\n",
    "\n",
    "if axis is not present in the output — you guessed it — axis was reduced."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.541621Z",
     "start_time": "2025-10-06T04:02:03.536651Z"
    }
   },
   "source": [
    "# average over batch\n",
    "bm.ein_reduce(ims, 'b h w c -> h w c', 'mean').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96, 3)"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 68
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.557906Z",
     "start_time": "2025-10-06T04:02:03.553659Z"
    }
   },
   "source": [
    "# the previous is identical to familiar:\n",
    "ims.mean(axis=0).shape\n",
    "# but is so much more readable"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96, 3)"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 69
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.574009Z",
     "start_time": "2025-10-06T04:02:03.569914Z"
    }
   },
   "source": [
    "# Example of reducing of several axes \n",
    "# besides mean, there are also min, max, sum, prod\n",
    "bm.ein_reduce(ims, 'b h w c -> h w', 'min').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96)"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 70
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.591850Z",
     "start_time": "2025-10-06T04:02:03.586999Z"
    }
   },
   "source": [
    "# this is mean-pooling with 2x2 kernel\n",
    "# image is split into 2x2 patches, each patch is averaged\n",
    "bm.ein_reduce(ims, 'b (h h2) (w w2) c -> h (b w) c', 'mean', h2=2, w2=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(48, 288, 3)"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 71
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.608147Z",
     "start_time": "2025-10-06T04:02:03.602082Z"
    }
   },
   "source": [
    "# max-pooling is similar\n",
    "# result is not as smooth as for mean-pooling\n",
    "bm.ein_reduce(ims, 'b (h h2) (w w2) c -> h (b w) c', 'max', h2=2, w2=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(48, 288, 3)"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 72
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.624452Z",
     "start_time": "2025-10-06T04:02:03.617364Z"
    }
   },
   "source": [
    "# yet another example. Can you compute result shape?\n",
    "bm.ein_reduce(ims, '(b1 b2) h w c -> (b2 h) (b1 w)', 'mean', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(288, 192)"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 73
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "source": [
    "## Stack and concatenate"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.653280Z",
     "start_time": "2025-10-06T04:02:03.646929Z"
    }
   },
   "source": [
    "# rearrange can also take care of lists of arrays with the same shape\n",
    "x = list(ims)\n",
    "print(type(x), 'with', len(x), 'tensors of shape', x[0].shape)\n",
    "# that's how we can stack inputs\n",
    "# \"list axis\" becomes first (\"b\" in this case), and we left it there\n",
    "res = bm.ein_rearrange(x, 'b h w c -> b h w c')\n",
    "\n",
    "[r.shape for r in res]"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'> with 6 tensors of shape (96, 96, 3)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[(96, 96, 3), (96, 96, 3), (96, 96, 3), (96, 96, 3), (96, 96, 3), (96, 96, 3)]"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 74
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.675197Z",
     "start_time": "2025-10-06T04:02:03.669081Z"
    }
   },
   "source": [
    "# but new axis can appear in the other place:\n",
    "bm.ein_rearrange(x, 'b h w c -> h w c b').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 96, 3, 6)"
      ]
     },
     "execution_count": 75,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 75
  },
  {
   "cell_type": "code",
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.696971Z",
     "start_time": "2025-10-06T04:02:03.689139Z"
    }
   },
   "source": [
    "# that's equivalent to numpy stacking, but written more explicitly\n",
    "numpy.array_equal(bm.ein_rearrange(x, 'b h w c -> h w c b'), numpy.stack(x, axis=3))"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 76
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.713898Z",
     "start_time": "2025-10-06T04:02:03.706420Z"
    }
   },
   "source": [
    "# ... or we can concatenate along axes\n",
    "bm.ein_rearrange(x, 'b h w c -> h (b w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 77
  },
  {
   "cell_type": "code",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.744778Z",
     "start_time": "2025-10-06T04:02:03.736784Z"
    }
   },
   "source": [
    "# which is equivalent to concatenation\n",
    "numpy.array_equal(bm.ein_rearrange(x, 'b h w c -> h (b w) c'), numpy.concatenate(x, axis=1))"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 78
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Addition or removal of axes\n",
    "\n",
    "You can write 1 to create a new axis of length 1. Similarly you can remove such axis.\n",
    "\n",
    "There is also a synonym `()` that you can use. That's a composition of zero axes and it also has a unit length."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.769312Z",
     "start_time": "2025-10-06T04:02:03.764339Z"
    }
   },
   "source": [
    "x = bm.ein_rearrange(ims, 'b h w c -> b 1 h w 1 c') # functionality of numpy.expand_dims\n",
    "print(x.shape)\n",
    "print(bm.ein_rearrange(x, 'b 1 h w 1 c -> b h w c').shape) # functionality of numpy.squeeze"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(6, 1, 96, 96, 1, 3)\n",
      "(6, 96, 96, 3)\n"
     ]
    }
   ],
   "execution_count": 79
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.789357Z",
     "start_time": "2025-10-06T04:02:03.782895Z"
    }
   },
   "source": [
    "# compute max in each image individually, then show a difference \n",
    "x = bm.ein_reduce(ims, 'b h w c -> b () () c', 'max') - ims\n",
    "bm.ein_rearrange(x, 'b h w c -> h (b w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 80
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Repeating elements\n",
    "\n",
    "Third operation we introduce is `repeat`"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.807388Z",
     "start_time": "2025-10-06T04:02:03.802852Z"
    }
   },
   "source": [
    "# repeat along a new axis. New axis can be placed anywhere\n",
    "bm.ein_repeat(ims[0], 'h w c -> h new_axis w c', new_axis=5).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 5, 96, 3)"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 81
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.824528Z",
     "start_time": "2025-10-06T04:02:03.819404Z"
    }
   },
   "source": [
    "# shortcut\n",
    "bm.ein_repeat(ims[0], 'h w c -> h 5 w c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 5, 96, 3)"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 82
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.841832Z",
     "start_time": "2025-10-06T04:02:03.836896Z"
    }
   },
   "source": [
    "# repeat along w (existing axis)\n",
    "bm.ein_repeat(ims[0], 'h w c -> h (repeat w) c', repeat=3).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 288, 3)"
      ]
     },
     "execution_count": 83,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 83
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.858649Z",
     "start_time": "2025-10-06T04:02:03.853596Z"
    }
   },
   "source": [
    "# repeat along two existing axes\n",
    "bm.ein_repeat(ims[0], 'h w c -> (2 h) (2 w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(192, 192, 3)"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 84
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.874648Z",
     "start_time": "2025-10-06T04:02:03.868730Z"
    }
   },
   "source": [
    "# order of axes matters as usual - you can repeat each element (pixel) 3 times \n",
    "# by changing order in parenthesis\n",
    "bm.ein_repeat(ims[0], 'h w c -> h (w repeat) c', repeat=3).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 288, 3)"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 85
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: `repeat` operation covers functionality identical to `numpy.repeat`, `numpy.tile` and actually more than that."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Reduce ⇆ repeat\n",
    "\n",
    "reduce and repeat are like opposite of each other: first one reduces amount of elements, second one increases.\n",
    "\n",
    "In the following example each image is repeated first, then we reduce over new axis to get back original tensor. Notice that operation patterns are \"reverse\" of each other"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.892052Z",
     "start_time": "2025-10-06T04:02:03.885972Z"
    }
   },
   "source": [
    "repeated = bm.ein_repeat(ims, 'b h w c -> b h new_axis w c', new_axis=2)\n",
    "reduced = bm.ein_reduce(repeated, 'b h new_axis w c -> b h w c', 'min')\n",
    "\n",
    "\n",
    "assert bm.allclose(ims, reduced)"
   ],
   "outputs": [],
   "execution_count": 86
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fancy examples in random order\n",
    "\n",
    "(a.k.a. mad designer gallery)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.912074Z",
     "start_time": "2025-10-06T04:02:03.906545Z"
    }
   },
   "source": [
    "# interweaving pixels of different pictures\n",
    "# all letters are observable\n",
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> (h b1) (w b2) c ', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(192, 288, 3)"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 87
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.936116Z",
     "start_time": "2025-10-06T04:02:03.930160Z"
    }
   },
   "source": [
    "# interweaving along vertical for couples of images\n",
    "bm.ein_rearrange(ims, '(b1 b2) h w c -> (h b1) (b2 w) c', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(192, 288, 3)"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 88
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.954788Z",
     "start_time": "2025-10-06T04:02:03.949854Z"
    }
   },
   "source": [
    "# interweaving lines for couples of images\n",
    "# exercise: achieve the same result without einops in your favourite framework\n",
    "bm.ein_reduce(ims, '(b1 b2) h w c -> h (b2 w) c', 'max', b1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 288, 3)"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 89
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.973780Z",
     "start_time": "2025-10-06T04:02:03.968104Z"
    }
   },
   "source": [
    "# color can be also composed into dimension\n",
    "# ... while image is downsampled\n",
    "bm.ein_reduce(ims, 'b (h 2) (w 2) c -> (c h) (b w)', 'mean').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(144, 288)"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 90
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:03.991014Z",
     "start_time": "2025-10-06T04:02:03.985802Z"
    }
   },
   "source": [
    "# disproportionate resize\n",
    "bm.ein_reduce(ims, 'b (h 4) (w 3) c -> (h) (b w)', 'mean').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(24, 192)"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 91
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.009173Z",
     "start_time": "2025-10-06T04:02:04.003636Z"
    }
   },
   "source": [
    "# spilt each image in two halves, compute mean of the two\n",
    "bm.ein_reduce(ims, 'b (h1 h2) w c -> h2 (b w)', 'mean', h1=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(48, 576)"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 92
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.028362Z",
     "start_time": "2025-10-06T04:02:04.022954Z"
    }
   },
   "source": [
    "# split in small patches and transpose each patch\n",
    "bm.ein_rearrange(ims, 'b (h1 h2) (w1 w2) c -> (h1 w2) (b w1 h2) c', h2=8, w2=8).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 93
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.049866Z",
     "start_time": "2025-10-06T04:02:04.044753Z"
    }
   },
   "source": [
    "# stop me someone!\n",
    "bm.ein_rearrange(ims, 'b (h1 h2 h3) (w1 w2 w3) c -> (h1 w2 h3) (b w1 h2 w3) c', h2=2, w2=2, w3=2, h3=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 94
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.069253Z",
     "start_time": "2025-10-06T04:02:04.063856Z"
    }
   },
   "source": [
    "bm.ein_rearrange(ims, '(b1 b2) (h1 h2) (w1 w2) c -> (h1 b1 h2) (w1 b2 w2) c', h1=3, w1=3, b2=3).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(192, 288, 3)"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 95
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.113892Z",
     "start_time": "2025-10-06T04:02:04.106619Z"
    }
   },
   "source": [
    "# patterns can be arbitrarily complicated\n",
    "bm.ein_reduce(ims, '(b1 b2) (h1 h2 h3) (w1 w2 w3) c -> (h1 w1 h3) (b1 w2 h2 w3 b2) c', 'mean', \n",
    "       h2=2, w1=2, w3=2, h3=2, b2=2).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 96
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.171625Z",
     "start_time": "2025-10-06T04:02:04.165992Z"
    }
   },
   "source": [
    "# subtract background in each image individually and normalize\n",
    "# pay attention to () - this is composition of 0 axis, a dummy axis with 1 element.\n",
    "im2 = bm.ein_reduce(ims, 'b h w c -> b () () c', 'max') - ims\n",
    "im2 /= bm.ein_reduce(im2, 'b h w c -> b () () c', 'max')\n",
    "bm.ein_rearrange(im2, 'b h w c -> h (b w) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 97
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.211528Z",
     "start_time": "2025-10-06T04:02:04.205623Z"
    }
   },
   "source": [
    "# pixelate: first downscale by averaging, then upscale back using the same pattern\n",
    "averaged = bm.ein_reduce(ims, 'b (h h2) (w w2) c -> b h w c', 'mean', h2=6, w2=8)\n",
    "bm.ein_repeat(averaged, 'b h w c -> (h h2) (b w w2) c', h2=6, w2=8).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 98
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.270835Z",
     "start_time": "2025-10-06T04:02:04.266340Z"
    }
   },
   "source": [
    "bm.ein_rearrange(ims, 'b h w c -> w (b h) c').shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576, 3)"
      ]
     },
     "execution_count": 99,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 99
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-06T04:02:04.311893Z",
     "start_time": "2025-10-06T04:02:04.306202Z"
    }
   },
   "source": [
    "# let's bring color dimension as part of horizontal axis\n",
    "# at the same time horizontal axis is downsampled by 2x\n",
    "bm.ein_reduce(ims, 'b (h h2) (w w2) c -> (h w2) (b w c)', 'mean', h2=3, w2=3).shape"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(96, 576)"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 100
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "## Summary\n",
    "\n",
    "- `rearrange` doesn't change number of elements and covers different numpy functions (like `transpose`, `reshape`, `stack`, `concatenate`,  `squeeze` and `expand_dims`)\n",
    "- `reduce` combines same reordering syntax with reductions (`mean`, `min`, `max`, `sum`, `prod`, and any others)\n",
    "- `repeat` additionally covers repeating and tiling\n",
    "- composition and decomposition of axes are a corner stone, they can and should be used together\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
